import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:xiaofanshu_flutter/controller/story_map_controller.dart';
import 'package:xiaofanshu_flutter/utils/guide_service.dart';
import 'package:xiaofanshu_flutter/config/guide_config.dart';
import 'package:xiaofanshu_flutter/controller/home_controller.dart';

class MapPage extends StatefulWidget {
  const MapPage({super.key});

  @override
  State<MapPage> createState() => _MapPageState();
}

class _MapPageState extends State<MapPage> {
  final StoryMapController controller = Get.find();

  // 引导相关
  final GlobalKey _zoomInKey = GlobalKey();
  final GlobalKey _filterKey = GlobalKey();
  GuideController? _guideController;
  bool _hasShownGuide = false;

  @override
  void initState() {
    super.initState();
    ever(controller.filteredPins, (_) => controller.updateMarkers());
    
    // 初始化引导
    try {
      _guideController = Get.find<GuideController>();
      
      // ========== 监听引导触发器 ==========
      ever(_guideController!.shouldShowMapGuide, (shouldShow) {
        if (shouldShow && mounted) {
          Get.log('📢 收到 MapPage 引导触发信号');
          _hasShownGuide = false; // 重置标志
          
          // 延迟一下，确保UI完全渲染
          Future.delayed(const Duration(milliseconds: 300), () {
            if (mounted) {
              _showGuideIfNeeded();
            }
          });
          
          _guideController?.resetMapGuideTrigger();
        }
      });
      
      Get.log('✅ MapPage 引导监听器已设置');
    } catch (e) {
      _guideController = null;
      Get.log('❌ 找不到 GuideController: $e');
    }
    // =====================================
  }
  
  Future<void> _showGuideIfNeeded() async {
    if (_guideController == null || _hasShownGuide) return;
    
    // 检查全局引导状态
    bool isGuideCompleted = await GuideService.isGuideCompleted();
    if (isGuideCompleted) {
      Get.log('⏭️ 全局引导已完成，跳过 MapPage 引导');
      _hasShownGuide = true;
      return;
    }
    
    try {
      if (mounted) {
        _hasShownGuide = true;
        await Future.delayed(const Duration(milliseconds: 500));
        
        if (!mounted) return;
        
        final steps = GuideConfig.createStoryMapGuideTargets(
          zoomInKey: _zoomInKey,
          filterKey: _filterKey,
        );
        
        if (steps.isNotEmpty) {
          GuideService.showGuide(
            context: context,
            steps: steps,
            onFinish: () async {
              Get.log('✅ MapPage 引导完成');
              await GuideService.setStoryMapGuideCompleted();
              
              // 修改：跳过列表页，直接切换到消息页面并触发引导
              try {
                final homeController = Get.find<HomeController>();
                await Future.delayed(const Duration(milliseconds: 300));
                homeController.changeIndex(3); // 切换到消息页（index 3）
                
                // 触发 MessagePage 引导
                await Future.delayed(const Duration(milliseconds: 500));
                _guideController?.triggerMessageGuide();
                Get.log('🎯 已触发 MessagePage 引导');
              } catch (e) {
                Get.log('❌ 切换页面失败: $e');
              }
            },
            onSkip: () async {
              Get.log('⏭️ 用户跳过 MapPage 引导');
              await GuideService.setGuideCompleted();
              _guideController?.completeAllGuides();
            },
          );
        }
      }
    } catch (e) {
      Get.log('❌ MapPage 引导显示失败: $e');
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  // 位置初始化现在由控制器处理，这里删除旧实现

  // 这些方法现在由控制器处理，这里删除旧实现

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() => Stack(
        children: [
          // 高德地图
          AMapWidget(
            privacyStatement: const AMapPrivacyStatement(hasShow: true, hasAgree: true, hasContains: true),
            initialCameraPosition: CameraPosition(
              target: controller.currentLocation.value ?? const LatLng(39.9042, 116.4074),
              zoom: controller.currentZoom.value,
            ),
            markers: Set<Marker>.of(controller.markers),
            polylines: Set<Polyline>.of(controller.polylines),
            onMapCreated: (mapController) {
              controller.onMapCreated(mapController);
            },
            onCameraMove: (cameraPosition) {
              controller.onCameraMove(cameraPosition);
            },
            onTap: (latLng) {
              // 地图点击事件 - 关闭弹窗
              if (controller.showFilterPopup.value) {
                controller.toggleFilterPopup();
              }
              if (controller.showStoryPreview.value) {
                controller.closeStoryPreview();
              }
            },
            myLocationStyleOptions: MyLocationStyleOptions(true),
          ),
          
          // 右上角功能按钮
          Positioned(
            top: 60,
            right: 20,
            child: Column(
              children: [
                _buildFilterButton(),
                const SizedBox(height: 15),
                _buildLocationButton(),
                const SizedBox(height: 15),
                _buildZoomInButton(),
                const SizedBox(height: 15),
                _buildZoomOutButton(),
              ],
            ),
          ),
          
          // 筛选弹窗
          if (controller.showFilterPopup.value) _buildFilterPopup(),
          
          // 故事预览弹窗
          if (controller.showStoryPreview.value) _buildStoryPreview(),
        ],
      )),
    );
  }

  Widget _buildFilterButton() {
    return GestureDetector(
      key: _filterKey,
      onTap: controller.toggleFilterPopup,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.filter_list, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildLocationButton() {
    return GestureDetector(
      onTap: controller.moveToCurrentLocation,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.my_location, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildZoomInButton() {
    return GestureDetector(
      key: _zoomInKey,
      onTap: () {
        if (controller.mapController != null) {
          controller.mapController?.moveCamera(
            CameraUpdate.zoomIn(),
          );
        }
      },
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.add, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildZoomOutButton() {
    return GestureDetector(
      onTap: () {
        if (controller.mapController != null) {
          controller.mapController?.moveCamera(
            CameraUpdate.zoomOut(),
          );
        }
      },
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.remove, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildFilterPopup() {
    return Obx(() => Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.95),
          borderRadius: BorderRadius.circular(20),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '选择类别',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 10),
            // 添加快速选择按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                TextButton(
                  onPressed: controller.selectAllCategories,
                  child: const Text('全选', style: TextStyle(color: Color(0xFFFF2442))),
                ),
                TextButton(
                  onPressed: controller.clearAllCategories,
                  child: const Text('清空', style: TextStyle(color: Color(0xFF666666))),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: _buildCategoryTags(),
            ),
            const SizedBox(height: 20),
            Row(
              children: [
                const Text('官方认证'),
                const Spacer(),
                Switch(
                  value: controller.showOfficialOnly.value,
                  onChanged: (value) => controller.toggleOfficialOnly(),
                  activeColor: const Color(0xFFFF2442),
                ),
              ],
            ),
            const SizedBox(height: 15),
            Row(
              children: [
                const Text('显示路线'),
                const Spacer(),
                Switch(
                  value: controller.showRoutes.value,
                  onChanged: (value) => controller.toggleRoutes(),
                  activeColor: const Color(0xFFFF2442),
                ),
              ],
            ),
            const SizedBox(height: 15),
            Row(
              children: [
                const Text('显示封面'),
                const Spacer(),
                Switch(
                  value: controller.showCovers.value,
                  onChanged: (value) => controller.toggleCovers(),
                  activeColor: const Color(0xFFFF2442),
                ),
              ],
            ),
            const SizedBox(height: 20),
            // 用户筛选
            TextField(
              decoration: InputDecoration(
                hintText: '输入用户昵称进行筛选',
                prefixIcon: const Icon(Icons.person_search, color: Color(0xFF999999)),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFFCCD5)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFFCCD5)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFF2442)),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              ),
              onChanged: (value) => controller.nicknameFilter.value = value,
            ),
            const SizedBox(height: 20),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: controller.confirmFilterAndReload,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFFF2442),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                ),
                child: const Text('确认', style: TextStyle(color: Colors.white)),
              ),
            ),
          ],
        ),
      ),
    ));
  }

  List<Widget> _buildCategoryTags() {
    if (controller.categories.isEmpty) {
      return const [Center(child: Text('加载分类中...'))];
    }

    return controller.categories.map((category) {
      String categoryName = category['categoryName'] ?? '未知分类';
      String categoryKey = categoryName.toLowerCase();
      bool isSelected = controller.selectedCategories[categoryKey] ?? false;
      
      return GestureDetector(
        onTap: () => controller.toggleCategory(categoryKey),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 8),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFFFF2442) : const Color(0xFFFFF0F5),
            border: Border.all(
              color: isSelected ? const Color(0xFFFF2442) : const Color(0xFFFFCCD5),
            ),
            borderRadius: BorderRadius.circular(15),
          ),
          child: Text(
            categoryName,
            style: TextStyle(
              color: isSelected ? Colors.white : const Color(0xFFFF2442),
              fontSize: 12,
            ),
          ),
        ),
      );
    }).toList();
  }

  Widget _buildStoryPreview() {
    return Obx(() {
      if (controller.filteredPins.isEmpty) return const SizedBox.shrink();
      
      // 确保当前索引在有效范围内
      if (controller.currentStoryIndex.value >= controller.filteredPins.length) {
        controller.currentStoryIndex.value = 0;
      }
      if (controller.currentStoryIndex.value < 0) {
        controller.currentStoryIndex.value = 0;
      }
      
      final currentStory = controller.filteredPins[controller.currentStoryIndex.value];
      
      return Positioned(
        bottom: 20,
        left: 20,
        right: 20,
        child: GestureDetector(
          onTap: () => controller.navigateToStoryDetail(currentStory),
          child: Container(
            padding: const EdgeInsets.all(15),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(15),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  currentStory.title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF333333),
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  currentStory.content,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF666666),
                  ),
                ),
                const SizedBox(height: 10),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => controller.navigateToUserProfile(currentStory.authorId ?? ''),
                      child: CircleAvatar(
                        radius: 15,
                        backgroundColor: const Color(0xFFFFF0F5),
                        backgroundImage: currentStory.authorAvatar != null 
                            ? NetworkImage(currentStory.authorAvatar!) 
                            : null,
                        child: currentStory.authorAvatar == null 
                            ? const Icon(Icons.person, size: 12, color: Colors.grey)
                            : null,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      currentStory.author,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Spacer(),
                    IconButton(
                      icon: const Icon(Icons.arrow_back_ios, size: 16),
                      onPressed: controller.previousStory,
                    ),
                    IconButton(
                      icon: const Icon(Icons.arrow_forward_ios, size: 16),
                      onPressed: controller.nextStory,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    });
  }
}